// 平台相关方法整合
const getExtInfo = () => {
    return new Promise((reslove, reject) => {
        wx.getExtConfig({
            success (res) {
              reslove(res.extConfig);
            },
            fail(err) {
                reject(err);
            },
          })
    });
    // return wx.getExtConfigSync ? wx.getExtConfigSync() : {};
};
/**
 * 显示 loading 
 * @param {String} title 提示内容
 * @param {Number} timeout 显示时间
 */
const showLoading = (title, timeout = 0) => {
    wx.showLoading({
        title,
        mask: true,
    });
    if (timeout) {
        setTimeout(() => {
            wx.hideLoading();
        }, timeout)
    }
}

/**
 * 关闭 loading
 */
const hideLoading = () => {
    wx.hideLoading();
};

/**
 * toast 提示信息
 * @param {String} title 提示内容
 */
const tipToast = (title, duration = 2000) => {
    wx.showToast({
        title,
        icon: 'none',
        duration,
    });
};

/**
 * toast success 提示信息
 * @param {String} title 提示内容
 */
const tipSuccess = (title, duration = 2000) => {
    wx.showToast({
        title,
        icon: 'success',
        duration,
    });
};

/**
 * toast error 提示信息
 * @param {String} title 提示内容
 */
const tipError = (title, duration = 2000) => {
    wx.showToast({
        title,
        icon: 'error',
        duration,
    });
};

// 界面相关

/**
 * 设置页面标题
 * @param {String} title 标题名称
 */
const setTitle = (title) => {
    wx.setNavigationBarTitle({
        title,
    });
};

/**
 * 设置手机状态栏字体颜色
 * @param {String} color 颜色
 */
const setPhoneBarColor = (color) => {
    wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: color,
        // animation: {
        //   duration: 400,
        //   timingFunc: 'easeIn'
        // }
    });
};

/**
 * 设置app背景色
 * @param {String} color 颜色
 */
const setAppBackground = (mode) => {
    wx.setBackgroundColor({
        backgroundColor: color,
        backgroundColorTop: color,
        backgroundColorBottom: color,
    });
};

/**
 * 隐藏主页
 */
const hideHomeButton = () => {
    wx.hideHomeButton({
        complete: (res) => {
            console.info('隐藏主页');
        },
    })
};

/**
 * 隐藏下拉刷新操作
 */
const hidePullDownLoading = () => {
    wx.stopPullDownRefresh();
};

/**
 * 获取菜单按钮（右上角胶囊按钮）的布局位置信息
 */
const getMenuButtonBoundingClientRect = () => {
    return wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null;
};

// 路由相关

/**
 * 处理页面跳转参数为字符串
 * @param {Object} param 页面参数
 */
const _dealPathParam = (path, param) => {
    let query = '';
    let _path = path;
    if (path.indexOf('?') > -1) {
        _path = path.split('?')[0];
        query += path.split('?')[1] + '&';
    }
    for (let key in param) {
        query += `${key}=${param[key]}&`;
    }
    return `${_path}${query ? '?' + query : ''}`;
};

/**
 * 路由跳转
 * @param {String} path 跳转路径
 * @param {Object} param 跳转参数
 */
const navTo = (path, param = {}) => {
    wx.navigateTo({
        url: _dealPathParam(path, param),
        fail: function (err) {
            console.error(`navTo 错误: ${JSON.stringify(err)}`);
        },
    })
};

/**
 * 路由跳转
 * @param {String} path 跳转路径
 * @param {Object} param 跳转参数
 */
const navToAction = (path, param = {}, action) => {
    wx.navigateTo({
        url: _dealPathParam(path, param),
        fail: function (err) {
            console.error(`navTo 错误: ${JSON.stringify(err)}`);
        },
        ...action,
    })
};

/**
 * 返回页面
 * @param {Number} pageNum 返回的页面数
 */
const navBack = (pageNum = 1) => {
    wx.navigateBack({
        delta: pageNum,
        fail: function (err) {
            console.error(`navTo 错误: ${JSON.stringify(err)}`);
            switchTab(TAB_BAR_PAGE.index);
        },
    });
};

/**
 * 页面跳转
 * @param {String} path 页面地址
 * @param {Object}} param 页面参数
 */
const redirectTo = (path, param = {}) => {
    wx.redirectTo({
        url: _dealPathParam(path, param),
        fail: function (err) {
            console.error(`redirectTo 错误: ${JSON.stringify(err)}`);
        },
    })
};

/**
 * 页面重载，关闭其他页面
 * @param {String} path 页面地址
 * @param {Object} param 页面参数
 */
const reLaunchTo = (path, param = {}) => {
    wx.reLaunch({
        url: _dealPathParam(path, param),
        fail: function (err) {
            console.error(`reLaunchTo 错误: ${JSON.stringify(err)}`);
        },
    })
};

/**
 * 跳转到 tabBar 页面
 * @param {String} path 页面地址
 */
const switchTab = (path) => {
    wx.switchTab({
        url: path,
        fail: function (err) {
            console.error(`switchTab 错误: ${JSON.stringify(err)}`);
        },
    })
}

// 本地数据保存方法

/**
 * 添加一个值到本地 storage
 * @param {String} name 名称
 * @param {Object} value 值
 * @param {Number} days 有效期，单位：天
 */
const setItem = (name, value, days = 1) => {
    const expires = new Date(Date.now() + days * 86400000);
    try {
        delItem(name);
        wx.setStorageSync(name, {
            value,
            expires,
        });
    } catch (error) {
        console.error(`setItem 出错: ${error}`);
    }
};

/**
 * 获取一个本地 storage 的值
 * @param {String} name 名称
 */
const getItem = (name) => {
    try {
        var obj = wx.getStorageSync(name)
        if (obj) {
            const now = new Date().getTime();
            const expires = new Date(obj.expires).getTime();
            if (now <= expires) {
                return obj.value;
            } else {
                console.warn(`getItem 警告: ${name} 过期！`);
            }
        }
        return '';
    } catch (error) {
        console.error(`getItem 出错: ${error}`);
    }
};

/**
 * 从本地 storage 删除一条数据记录
 * @param {String} name 名称
 */
const delItem = (name) => {
    try {
        wx.removeStorageSync(name);
    } catch (error) {
        console.error(`delItem 出错: ${error}`);
    }
};

/**
 * 清除所有的本地 storage 数据
 */
const clearItems = () => {
    try {
        wx.clearStorageSync();
    } catch (error) {
        console.error(`clearItems 出错: ${error}`);
    }
};

/**
 * 设置没有时效性的本地数据
 * @param {String} name 名称
 * @param {Object} value 值
 */
const setForEverData = (name, value) => {
    try {
        wx.setStorageSync(name, value);
    } catch (error) {
        console.error(`setForEverData 出错: ${error}`);
        setForEverData(name, value);
    }
};

/**
 * 获取没有时效性的本地数据
 * @param {String} name 名称
 */
const getForEverData = (name) => {
    try {
        return wx.getStorageSync(name);
    } catch (error) {
        console.error(`getForEverData 出错: ${error}`);
        return '';
    }
};

// 平台相关类方法封装

/**
 * 获取登录code
 */
const getPlatformCode = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            success: res => {
                resolve(res.code);
            },
            fail: err => {
                reject(false);
            }
        });
    });
};

/**
 * 获取设置setting
 */
const getSetting = () => {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: res => {
                resolve(res.authSetting);
            },
            fail: err => {
                reject(false);
            }
        });
    });
};

// 获取用户信息
const getUserInfo = (desc = '用于完善用户资料') => {
    return new Promise((resolve, reject) => {
        if (canIUse('getUserProfile')) {
            wx.getUserProfile({
                desc,
                success: res => {
                    resolve(res.userInfo);
                },
                fail: err => {
                    reject(err);
                }
            })
        } else {
            wx.getUserInfo({
                success: res => {
                    resolve(res.userInfo);
                },
                fail: err => {
                    reject(err);
                }
            })
        }
    });
};

/**
 * 获取用户信息授权状态
 * @param {Object} authInfo 
 */
const isAuthUserInfo = (authInfo) => {
    return authInfo['scope.userInfo'];
};

/**
 * 是否授权获取位置信息
 * @param {Object} authInfo 
 */
const isAuthGetLocation = (authInfo) => {
    return authInfo['scope.userLocation'];
};

/**
 * 获取系统信息
 */
const getSysInfo = () => {
    try {
        return wx.getSystemInfoSync();
    } catch (error) {
        return {};
    }
};

/**
 * 打开扫码
 */
const openScan = () => {
    return new Promise((reslove, reject) => {
        wx.scanCode({
            success(res) {
                reslove(res.result);
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

/**
 * 拨打电话
 * @param {number} phoneNumber 电话号码
 */
const callPhone = (phoneNumber) => {
    if (!isValidPhone(phoneNumber)) {
        wx.showToast({
            icon: 'none',
            title: '号码错误',
        })
        return;
    }
    wx.makePhoneCall({
        phoneNumber,
    })
};

/**
 * 地理位置信息
 */
const getLocationInfo = () => {
    return new Promise((resolve, reject) => {
        wx.getLocation({
            type: 'wgs84',
            success(res) {
                const latitude = res.latitude
                const longitude = res.longitude
                resolve({
                    latitude,
                    longitude,
                });
            },
            fail() {
                resolve(false)
            },
        })
    });
};

/**
 * 打开地图选择位置
 */
const chooseLocation = () => {
    return new Promise((resolve, reject) => {
        wx.chooseLocation({
            success(res) {
                resolve(res);
            },
        });
    });
};

/**
 * 打开地图选择位置
 */
const chooseAddress = () => {
    return new Promise((resolve, reject) => {
        wx.chooseAddress({
            success: function (res) {
                resolve({
                    username: res.userName,
                    mobile: res.telNumber,
                    address: `${res.cityName}${res.countyName}${res.detailInfo}`,
                    code: res.postalCode,
                });
            },
            fail: function (err) {
                reject(false);
            },
        })
    });
};

// 选择图片
const chooseImage = (params = {}) => {
    const { count = 1, sizeType = ['original', 'compressed'] } = params;
    return new Promise((resolve, reject) => {
        wx.chooseImage({
            count,
            sizeType,
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                resolve(tempFilePaths);
            },
            fail(err) {
                reject(err);
            },
        });
    });
};

// 获取图片信息
const getImageInfo = (filePath) => {
    return new Promise((resolve, reject) => {
        wx.getImageInfo({
            src: filePath,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        });
    });
};

// 保存图片到系统相册
const saveImage = (filePath) => {
    return new Promise((resolve, reject) => {
        wx.saveImageToPhotosAlbum({
            filePath,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

// 压缩图片
const compressImage = (filePath, quality = 80) => {
    return new Promise((resolve, reject) => {
        wx.compressImage({
            src: filePath,
            quality,
            success(res) {
                const tempFilePath = res.tempFilePath;
                resolve(tempFilePath);
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

// 选择视频
const chooseVideo = (duration) => {
    return new Promise((resolve, reject) => {
        wx.chooseVideo({
            maxDuration: duration || 60,
            success(res) {
                const tempFilePath = res.tempFilePath;
                resolve(tempFilePath);
            },
            fail(err) {
                reject(err);
            },
        });
    });
};

// 获取视频信息
const getVideoInfo = (filePath) => {
    return new Promise((resolve, reject) => {
        wx.getVideoInfo({
            src: filePath,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        });
    });
};

// 选择图片、视频
const chooseMedia = ({ count = 1, duration = 60 }) => {
    return new Promise((resolve, reject) => {
        wx.chooseMedia({
            count,
            maxDuration: duration,
            success(res) {
                const tempFilePath = res.tempFiles.tempFilePath;
                resolve(tempFilePath);
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

// 下载文件
const downloadFile = (url) => {
    return new Promise((resolve, reject) => {
        wx.downloadFile({
            url,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        })
    });
};

// 读取文件
const readFile = (filePath, encoding = 'base64') => {
    return new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
            filePath,
            encoding,
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            },
        }) 
    });
};

// 复制文本
const copyText = (text, callback) => {
    wx.setClipboardData({
        data: text,
        success (res) {
            callback && isFunction(callback) ? callback() : tipSuccess('复制成功');
        }
      })
};

const hideTabbar = () => {
    wx.hideTabBar({
        animation: true,
        fail: function () {
            hideTabbar();
        },
    });
};

const showTabbar = () => {
    wx.showTabBar({
        animation: false,
        fail: function () {
            showTabbar();
        },
    });
};

const canIUse = (name) => {
    return wx.canIUse(name);
}

const openSetting = () => {
    wx.openSetting();
};

const platformPay = (prepay) => {
    return new Promise((reslove, reject) => {
        wx.requestPayment({
            timeStamp: prepay.timeStamp,
            nonceStr: prepay.nonceStr,
            package: prepay.package,
            signType: prepay.signType,
            paySign: prepay.paySign,
            success(res) {
                console.log('支付成功', res);
                reslove(true);
            },
            fail(error) {
                console.log('支付失败', error);
                reslove(false);
            },
        });
    });
};

module.exports = {
    getExtInfo,
    showLoading,
    hideLoading,
    tipToast,
    tipSuccess,
    tipError,
    setTitle,
    setPhoneBarColor,
    setAppBackground,
    hideHomeButton,
    hidePullDownLoading,
    getMenuButtonBoundingClientRect,
    navTo,
    navToAction,
    navBack,
    redirectTo,
    reLaunchTo,
    switchTab,
    setItem,
    getItem,
    delItem,
    clearItems,
    setForEverData,
    getForEverData,
    getPlatformCode,
    getSetting,
    getUserInfo,
    isAuthUserInfo,
    isAuthGetLocation,
    getSysInfo,
    openScan,
    callPhone,
    getLocationInfo,
    chooseLocation,
    chooseAddress,
    chooseImage,
    getImageInfo,
    saveImage,
    compressImage,
    chooseVideo,
    getVideoInfo,
    chooseMedia,
    downloadFile,
    readFile,
    copyText,
    hideTabbar,
    showTabbar,
    canIUse,
    openSetting,
    platformPay,
};